<?php

declare(strict_types=1);

namespace app\admin\controller;

use think\Request;
use sheep\controller\Backend;
use sheep\exception\SheepException;
use sheep\model\Config;
use sheep\library\install\Install as InstallLibrary;

class Install extends Backend
{

    /**
     * 安装入口
     */
    public function index()
    {
        // 当前数据库配置信息
        $configDatabase = config('database.connections.mysql');
        $database = [
            'mysql_hostname' => $configDatabase['hostname'],
            'mysql_database' => $configDatabase['database'],
            'mysql_username' => $configDatabase['username'],
            'mysql_password' => $configDatabase['password'],
            'mysql_hostport' => $configDatabase['hostport'],
            'mysql_prefix' => $configDatabase['prefix'],
        ];
        // 当前 redis 配置
        $configRedis = get_redis_connection('default');
        $redis = [
            'redis_host' => $configRedis['host'],
            'redis_port' => $configRedis['port'],
            'redis_password' => $configRedis['password'],
            'redis_select' => $configRedis['select'],
            'check_redis' => 1,
        ];
        
        $data = [
            'mysql' => $database,
            'redis' => $redis
        ];

        return success('获取成功', $data);
    }



    /**
     * 检测
     */
    public function check() 
    {
        $install = new InstallLibrary();

        // 检测系统环境
        $result = $install->checkSystemEnv();

        return success('检测完成', $result);
    }



    /**
     * 安装
     */
    public function install(Request $request)
    {
        $install = new InstallLibrary();

        // 配置环境参数
        $result = $install->viewConfig();

        // 检测系统环境
        $result = $install->checkSystemEnv();
        if ($result['error']) {
            foreach ($result['output'] as $output) {
                if ($output['error'] == 1) {
                    throw new SheepException($output['msg']);
                }
            }
        }

        // 生成 jwt 密钥
        $key = $install->setJwtKey();

        // 执行数据迁移
        $result = $install->databaseMigrate();
        if ($result['error']) {
            throw new SheepException('数据迁移执行失败,错误原因：' . json_encode($result) . ',请手动执行 php think migrate:run');
        }

        // 执行数据填充
        $result = $install->databaseSeed();
        if ($result['error']) {
            $need_commands = [];
            foreach ($result['statusItem'] as $item) {
                if ($item['error']) {
                    $need_commands[] = 'php think seed:run --seed=' . $item['item'];
                }
            }
            
            throw new SheepException('初始化数据执行失败,请手动执行 ' . implode(', ', $need_commands));
        }

        // 到这里就算安装完成了，写入 install.lock
        $install->writeInstallLock();

        // $backend_uri = $request->param('backend_uri');
        $account = $request->param('admin_account');
        $password = $request->param('admin_password');
        // 设置后台入口
        // $install->setEnvVar('APP.BACKEND_URI', $backend_uri);

        // 创建管理员账号，并设置为超级管理员
        $create_ok = $install->createAdmin($account, $password);

        $install->success();

        return success('安装完成' . ($create_ok ? '' : ' - 管理员账号已存在,如忘记密码可以使用 php think sheep:help admin_reset_password 重置密码'));
    }
}
